import { RouterMount, createRouter, runtimeQuit } from 'uni-simple-router'
import { minCache } from '@/utils/min-cache'
import store from '@/store/index'
import { formHasValue } from '@/utils/form-has-value'
const router = createRouter({
  platform: process.env.VUE_APP_PLATFORM as any,
  routes: [
    ...ROUTES,
    {
      path: '*',
      redirect: () => {
        return { name: 'Index' }
      },
    },
  ],
  h5: {
    paramsToQuery: true,
    vueRouterDev: false, //完全使用vue-router开发 默认 false
  },
  routerErrorEach: ({ type }) => {
    // #ifdef APP-PLUS
    if (type === 3) {
      router.$lockStatus = false
      runtimeQuit()
    }
    // #endif
  },
})
router.beforeEach(async (to, from, next) => {
  // 有My单词，但是还需要包括内容例如  MyOrder 有效 ， My无效
  // 过滤空值，解决在正式服务器上跳转不过去
  to.query = formHasValue(to.query)
  from.query = formHasValue(from.query)

  const my = /^My./i.test(to.name as string)
  try {
    if (minCache.get('ut')) {
      const userInfo = (store as any).getters['login/getUserInfo']

      if (minCache.get('ut') && !userInfo.userId) {
        await store.dispatch('login/getUserInfo')
      }

      if ((store as any).getters['cache/getIsFetch'] === 0) {
        await store.dispatch('cache/fetchData')
        await store.dispatch('outWork/setDicts')
      }

      next()
    } else {
      if (to.name === 'UserLogin') {
        next()
      } else {
        uni.hideTabBar()
        next({
          NAVTYPE: 'replaceAll',
          name: 'UserLogin',
          params: {
            redirect: to.name,
            ...to.query,
          },
        })
      }
    }
  } catch (e) {
    next()
  }
})

router.afterEach(async (to: any, from: any) => {
  // console.log(to, from)
})

export { router, RouterMount }
